package cn.gs.util.net;

// @author gs
import cn.gs.util.stream.LineByLineFileReader;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class Downloader {

    private static InputStream get(String url) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    }

    public static boolean get2file(String url, File file) {
        try {
            file.getParentFile().mkdirs();
            file.createNewFile();
            byte[] bs = new byte[1024];
            int read;
            InputStream is = get(url);
            OutputStream os = new FileOutputStream(file);
            while ((read = is.read(bs)) > 0) {
                os.write(bs, 0, read);
            }
            os.close();
            is.close();
            return true;
        } catch (IOException ex) {
            Logger.getLogger(Downloader.class.getName()).log(Level.WARNING, null, ex);
            return false;
        }
    }
}
